package com.block.common.util;

import com.block.common.exception.BotApiException;
import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 
 * @date 2021/12/1 9:42 下午
 */
public class GraphQLUtils {

  private static   final OkHttpClient client = new OkHttpClient().newBuilder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .callTimeout(30, TimeUnit.SECONDS)
            .build();
    /**
     * 基础sql转换
     * @param queryUrl
     * @return
     */
    public static String addBaseQl(String queryUrl){
        String baseQL= "{\"query\":\"{" + queryUrl + "}\"}";
        return baseQL;
    }


    /**
     * 替换不需要的字符
     * @param st
     * @return
     */
    public static String replaceQl(String st){
        st=st.replace(" ","");
        st= st.replace("\n"," ");
        st= st.replace("\t"," ");
        st=st.replace("\"","\\\"");
        return st;
    }

    /**
     * 请求
     * @param url
     * @param queryUrl
     * @return
     * @throws IOException
     */
    public static String requestQl(String url,String queryUrl) throws IOException {
        String str="";
        MediaType JSON_TYPE = MediaType.parse("application/json");
        Request request=new Request.Builder().url(url).post(RequestBody.create(queryUrl, JSON_TYPE)).build();
        Response response = client.newCall(request).execute();
        if (response != null && response.body() != null) {
            str = response.body().string();
            response.close();
            System.out.println("xxxxx请求数据返回结果:"+str);
            return str;
        } else {
            throw new BotApiException(BotApiException.ENV_ERROR,
                    "[Invoking] Cannot get the response from server");
        }
    }
}
